package com.sihai.ehr.web.action.rank;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.*;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.service.DutyService;
import com.sihai.ehr.service.JobSpecificationService;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.JobSpecificationPojo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wxn
 * @since 2012-6-9 9:39
 *        <p/>
 *        工作说明书设置Action
 */
@Results({
        @Result(name = "list", location = "job_specification_list.jsp"),
        @Result(name = "add", location = "job_specification_add.jsp"),
        @Result(name = "set_list", location = "job_specification_set_list.jsp"),
        @Result(name = "audit_list", location = "job_specification_audit_list.jsp"),
        @Result(name = "audit_detail", location = "job_specification_audit.jsp"),
        @Result(name = "main", location = "rank_main.jsp")
})
public class JobSpecificationAction extends EHRAction {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 7204414972672240978L;

    @BeanInject
    private DutyService dutyService;

    @BeanInject
    private JobSpecificationService jobSpecificationService;

    private LimitedList<JobSpecification> jobSpecifications;

    private LimitedList<JobSpecificationPojo> jobSpecificationPojos;

    private Long currentDutyId;
    private Duty duty;
    private List<Duty> duties;

    private JobSpecification jobSpecification;

    private String jobSpecificationIds;

    private List<JobSpecificationProject> projects;

    private String operation;

    private List<List<JobSpecificationAuditing>> audits;

    @Action("/rank/job_specification")
    @Override
    public String execute() throws Exception {
        if (StringUtils.equals(operation, "set")) {
            listAction = "/rank/job_specification_set_list.xhtml?operation=set";
            listTitle = "工作说明书设置";
        } else if (StringUtils.equals(operation, "audit")) {
            listAction = "/rank/job_specification_audit_list.xhtml?operation=audit";
            listTitle = "工作说明书审核";
        } else if (StringUtils.equals(operation, "search")) {
            listAction = "/rank/job_specification_list.xhtml?operation=search";
            listTitle = "工作说明书查询";
        }
        return "main";
    }

    //工作说明书设置列表(JobSpecification 与 Duty right join 查询)
    @Action("/rank/job_specification_set_list")
    public String settings() throws Exception {
        jobSpecificationPojos = jobSpecificationService.findByOrganization(organizationId, createLimit(), createSorter());

        return "set_list";
    }

    //得到工作说明书列表(已有说明书)
    @Action("/rank/job_specification_list")
    public String list() throws Exception {
       jobSpecifications = jobSpecificationService.findByOrganizationAndStatus(organizationId, new AuditStatus[]{AuditStatus.pass_audit}, createLimit(), createSorter());

        return "list";
    }

    //跳转到添加/编辑页面
    @Action("/rank/job_specification_add")
    public String add() throws Exception {
        operation = "set";
        if (jobSpecification != null && jobSpecification.getId() != null && jobSpecification.getId() > 0) {//edit
            jobSpecification = jobSpecificationService.get(jobSpecification.getId());
            projects = jobSpecificationService.getProjects(jobSpecification.getId());
            duty = jobSpecification.getDuty();
        } else {//create
            if (currentDutyId == null || currentDutyId == 0) {
                return execute();
            }
            duty = dutyService.get(currentDutyId);
        }

        duties = dutyService.searchWithPath((Long) null, null, null);

        return "add";
    }

    //添加修改工作说明书
    @Action("/rank/job_specification_create")
    public String create() throws Exception {
        operation = "set";
        if (jobSpecification == null) {
            return execute();
        }

        List<JobSpecificationProject> projects = prepareProjectFromRequest(jobSpecification);
        jobSpecification.setProjects(projects);
        if (jobSpecification.getId() != null && jobSpecification.getId() > 0) {//edit
            JobSpecification js = jobSpecificationService.get(jobSpecification.getId());
            js.setPreDuty(jobSpecification.getPreDuty());
            js.setNextDuty(jobSpecification.getNextDuty());
            js.setTaskContent(jobSpecification.getTaskContent());
            js.setSex(jobSpecification.getSex());
            js.setEducation(jobSpecification.getEducation());
            js.setTraining(jobSpecification.getTraining());
            js.setCertificate(jobSpecification.getCertificate());
            js.setEnglish(jobSpecification.getEnglish());
            js.setExperience(jobSpecification.getExperience());
            js.setJobTime(jobSpecification.getJobTime());
            js.setJobEnvironment(jobSpecification.getJobEnvironment());
            js.setJsJob(jobSpecification.getJsJob());
            js.setLhJob(jobSpecification.getLhJob());
            js.setDlJob(jobSpecification.getDlJob());
            js.setJszcJob(jobSpecification.getJszcJob());
            if(projects != null){
                if(js.getProjects() != null){
                    projects.addAll(js.getProjects());
                }
                js.setProjects(projects);
            }
            jobSpecificationService.save(js);
        } else { //create
            jobSpecification.setAuditStatus(AuditStatus.wait_audit);
            jobSpecificationService.save(jobSpecification);
        }

        return execute();
    }

    //工作说明书查看
    @Action("/rank/job_specification_view")
    public String view() throws Exception {
        if (jobSpecification == null || jobSpecification.getId() == null || jobSpecification.getId() == 0) {
            return execute();
        }

        jobSpecification = jobSpecificationService.get(jobSpecification.getId());
        if (jobSpecification == null) {
            return execute();
        }
        projects = jobSpecificationService.getProjects(jobSpecification.getId());

        return "view";
    }

    //工作说明书删除
    @Action("/rank/job_specification_delete")
    public String remove() throws Exception {
        operation = "set";
        if (StringUtils.isBlank(jobSpecificationIds)) {
            return execute();
        }
        jobSpecificationService.remove(jobSpecificationIds);

        return execute();
    }

    //工作说明书审核列表
    @Action("/rank/job_specification_audit_list")
    public String auditList() throws Exception {
        jobSpecifications = jobSpecificationService.findByOrganizationAndStatus(organizationId, new AuditStatus[]{AuditStatus.wait_audit, AuditStatus.within_audit}, createLimit(), createSorter());

        return "audit_list";
    }

    //跳转到审核页面
    @Action("/rank/job_specification_audit_detail")
    public String auditDetail() throws Exception {
        if (jobSpecification == null || jobSpecification.getId() == null) {
            return auditList();
        }

        jobSpecification = jobSpecificationService.get(jobSpecification.getId());
        if (jobSpecification == null) {
            return auditList();
        }
        projects = jobSpecificationService.getProjects(jobSpecification.getId());

        audits = jobSpecificationService.findJobSpecificationAuditing(jobSpecification.getId());
        if(audits == null || audits.isEmpty()){
            jobSpecificationService.saveJobSpecificationAuditingProcess(jobSpecification);
            audits = jobSpecificationService.findJobSpecificationAuditing(jobSpecification.getId());
        }
        //检查当前登录用户是否可以审核当前结点
        if(jobSpecification.getDuty() != null && audits != null && !audits.isEmpty()){
            checkCanAudit(jobSpecification.getDuty(), audits.get(audits.size()-1));
        }
        currentAuditType = AuditType.audit_job_specification.toString();

        return "audit_detail";
    }

    private List<JobSpecificationProject> prepareProjectFromRequest(JobSpecification jobSpecification) {
        HttpServletRequest request = ServletActionContext.getRequest();
        String[] projectContents = request.getParameterValues("p_content");
        String[] projectRateDays = request.getParameterValues("p_rateDay");
        String[] projectRateWeeks = request.getParameterValues("p_rateWeek");
        String[] projectRateMonths = request.getParameterValues("p_rateMonth");
        String[] projectRateSeasons = request.getParameterValues("p_rateSeason");
        String[] projectPercents = request.getParameterValues("p_percent");
        String[] projectDegrees = request.getParameterValues("p_degree");
        if (isEmpty(projectContents) || isEmpty(projectRateDays) || isEmpty(projectRateWeeks) || isEmpty(projectRateMonths) || isEmpty(projectRateSeasons) || isEmpty(projectPercents) || isEmpty(projectDegrees)) {
            return null;
        }
        int length = projectContents.length;
        List<JobSpecificationProject> projects = new ArrayList<JobSpecificationProject>(length);
        for (int i = 0; i < length; i++) {
            JobSpecificationProject project = new JobSpecificationProject();
            project.setContent(projectContents[i]);
            project.setRateDay(projectRateDays[i]);
            project.setRateWeek(projectRateWeeks[i]);
            project.setRateMonth(projectRateWeeks[i]);
            project.setRateMonth(projectRateMonths[i]);
            project.setPercent(NumberUtils.createFloat(projectPercents[i]));
            project.setDegree(projectDegrees[i]);
            project.setJobSpecification(jobSpecification);
            projects.add(project);
        }
        return projects;
    }

    private boolean isEmpty(String[] array) {
        return array == null || array.length == 0;
    }

    public LimitedList<JobSpecification> getJobSpecifications() {
        return jobSpecifications;
    }

    public void setJobSpecifications(LimitedList<JobSpecification> jobSpecifications) {
        this.jobSpecifications = jobSpecifications;
    }

    public JobSpecification getJobSpecification() {
        return jobSpecification;
    }

    public void setJobSpecification(JobSpecification jobSpecification) {
        this.jobSpecification = jobSpecification;
    }

    public String getJobSpecificationIds() {
        return jobSpecificationIds;
    }

    public void setJobSpecificationIds(String jobSpecificationIds) {
        this.jobSpecificationIds = jobSpecificationIds;
    }

    public Long getCurrentDutyId() {
        return currentDutyId;
    }

    public void setCurrentDutyId(Long currentDutyId) {
        this.currentDutyId = currentDutyId;
    }

    public Duty getDuty() {
        return duty;
    }

    public void setDuty(Duty duty) {
        this.duty = duty;
    }

    public List<Duty> getDuties() {
        return duties;
    }

    public void setDuties(List<Duty> duties) {
        this.duties = duties;
    }

    public List<JobSpecificationProject> getProjects() {
        return projects;
    }

    public void setProjects(List<JobSpecificationProject> projects) {
        this.projects = projects;
    }

    public String getOperation() {
        return operation;
    }

    public void setOperation(String operation) {
        this.operation = operation;
    }

    public LimitedList<JobSpecificationPojo> getJobSpecificationPojos() {
        return jobSpecificationPojos;
    }

    public void setJobSpecificationPojos(LimitedList<JobSpecificationPojo> jobSpecificationPojos) {
        this.jobSpecificationPojos = jobSpecificationPojos;
    }

    public List<List<JobSpecificationAuditing>> getAudits() {
        return audits;
    }

    public void setAudits(List<List<JobSpecificationAuditing>> audits) {
        this.audits = audits;
    }
}
